# -*- coding: utf-8 -*-


import sys, pygame
from random import randrange
from pygame.locals import KEYDOWN, K_UP, K_RIGHT, K_DOWN, K_LEFT, QUIT, K_r, K_q
from itertools import count




pygame.init()

clock = pygame.time.Clock()
size = width, height = 800, 600
screen = pygame.display.set_mode(size)


up, right, down, left = (0, -10), (10, 0), (0, 10), (-10, 0)  


snake_dir, food = down, None 

snake = [pygame.Rect(10, 10 + value * 10, 10, 10) for value in range(20)]

foreground, background = (255, 255, 255), (0, 0, 0)

for counter in count():
    
    clock.tick(min(10 , 30))

    event = pygame.event.poll()

    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    elif event.type == KEYDOWN:
        if event.key == K_UP and snake_dir != down:
            snake_dir = up
        elif event.key == K_RIGHT and snake_dir != left:
            snake_dir = right
        elif event.key == K_DOWN and snake_dir != up:
            snake_dir = down
        elif event.key == K_LEFT and snake_dir != right:
            snake_dir = left
            
    next = snake[-1].move(snake_dir)
    
    snake.append(next)
    del snake[0]
    screen.fill(background)
    for rect in snake:
        pygame.draw.rect(screen, foreground, rect)

        if next == food:
            food = None

        

    if food is None and counter % 5 == 0:
        food = pygame.Rect(randrange(48) * 10, randrange(48) * 10, 10, 10)

    screen.fill(background)

    for rect in snake:
        pygame.draw.rect(screen, foreground, rect)

    if food:
        pygame.draw.rect(screen, foreground, food)


    
    pygame.display.flip()
